/*
 * @Author: Eli.Chen
 * @Date: 2025-03-10 16:18:46
 * @LastEditors: Eli.Chen
 * @LastEditTime: 2025-04-30 10:55:46
 * @Description: 社区列表
 */

import React, { useEffect, useState } from 'react';
import {
    LikeOutlined,
    MessageOutlined,
    StarOutlined,
    DeleteOutlined,
    UserOutlined,
    PlayCircleOutlined,
} from '@ant-design/icons';
import { Avatar, List, Space, Skeleton, Button, Card, Input, Tooltip, message, Modal } from 'antd';
import { ReactComponent as SendIcon } from '@/assets/images/icons/SendIcon.svg';
import { useSelector, useDispatch } from 'react-redux';

import { sendComment } from '@/api/community';
import { urlMap, imagesMap } from '@/utils';
import { getCommunityList, toggleAction, deleteComment } from '@/api/community';
import { setThreadIsRefresh } from '@/store/reducers/active';

function ComList() {
    const [expandedItems, setExpandedItems] = useState({});
    const [isLoading, setIsLoading] = useState(true);
    const [commentText, setCommentText] = useState({});
    const [hoveredComment, setHoveredComment] = useState(null);

    // 列表数据
    const [comList, setComList] = useState([]);
    const { userInfo } = useSelector((state) => state.auth);
    const { threadIsRefresh } = useSelector((state) => state.active);
    const { cityCode } = useSelector((state) => state.uLocation || {});
    const dispatch = useDispatch();

    const handleLike = async (postId) => {
        try {
            const res = await toggleAction('like', postId);
            if (res.code === 200 && userInfo) {
                dispatch(setThreadIsRefresh(!threadIsRefresh));
            }
        } catch (error) {
            console.error('点赞操作失败:', error);
        }
    };

    const handleFavorite = async (postId) => {
        try {
            const res = await toggleAction('favorite', postId);
            if (res.code === 200 && userInfo) {
                dispatch(setThreadIsRefresh(!threadIsRefresh));
            }
        } catch (error) {
            console.error('收藏操作失败:', error);
        }
    };

    const handleCommentSubmit = (tPostId, index) => {
        if (!commentText[index]) {
            message.error('评论不能为空');
            return;
        }
        sendComment({
            postId: tPostId,
            userId: userInfo.userId,
            content: commentText[index],
        }).then((res) => {
            if (res.code === 200) {
                setCommentText({});
                message.success('评论成功');
                dispatch(setThreadIsRefresh(!threadIsRefresh));
            }
        });
    };

    const handleDeleteComment = (commentId) => {
        deleteComment(commentId).then((res) => {
            if (res.code === 200) {
                message.success('删除成功');
                dispatch(setThreadIsRefresh(!threadIsRefresh));
            }
        });
    };

    useEffect(() => {
        if (userInfo) {
            const { userId } = userInfo;
            getCommunityList(userId, cityCode).then((res) => {
                const processedData = res?.data?.map((item) => ({
                    ...item,
                    comments:
                        Array.isArray(item.comments) && item.comments.length === 1 && item.comments[0] === null
                            ? []
                            : item.comments,
                }));
                setIsLoading(false);
                setComList(processedData);
            });
        }
    }, [userInfo, threadIsRefresh]);

    return (
        <List
            itemLayout="vertical"
            size="large"
            dataSource={comList}
            // style={{
            //   minHeight: '30vh',
            //   maxHeight: '70vh',
            //   overflowY: 'auto'
            // }}
            renderItem={(item, index) =>
                !isLoading ? (
                    <>
                        <List.Item
                            key={item.postId}
                            actions={[
                                <Button
                                    key="list-vertical-star-o"
                                    icon={<StarOutlined />}
                                    type="link"
                                    onClick={() => handleFavorite(item.postId)}
                                    style={{
                                        color: item.favoritedByCurrentUser ? 'gold' : 'inherit',
                                        padding: '0 8px',
                                    }}
                                >
                                    {item.favoritesCount}
                                </Button>,
                                <Button
                                    key="list-vertical-like-o"
                                    icon={<LikeOutlined />}
                                    type="link"
                                    onClick={() => handleLike(item.postId)}
                                    style={{
                                        color: item.likedByCurrentUser ? 'gold' : 'inherit',
                                        padding: '0 8px',
                                    }}
                                >
                                    {item.likesCount}
                                </Button>,
                                <div key="message-and-info" style={{ display: 'flex', alignItems: 'center' }}>
                                    <Button
                                        key="list-vertical-message"
                                        icon={<MessageOutlined />}
                                        type="link"
                                        onClick={() =>
                                            setExpandedItems((prev) => ({
                                                ...prev,
                                                [index]: !prev[index],
                                            }))
                                        }
                                        style={{
                                            color: expandedItems[index] ? 'gold' : 'inherit',
                                            padding: '0 8px',
                                        }}
                                    >
                                        {item.comments?.length}
                                    </Button>
                                    <div style={{ marginLeft: 16 }}>
                                        <div style={{ fontSize: 12, color: 'rgba(0, 0, 0, 0.45)' }}>
                                            {item.createTime && new Date(item.createTime).toLocaleDateString()}
                                        </div>
                                        <div style={{ marginTop: 4 }}>
                                            {(typeof item.tags === 'string' ? item.tags.split(',') : item.tags || [])
                                                .filter((tag) => tag) // 过滤空标签
                                                .map((tag) => {
                                                    const tagNumber = parseInt(tag, 10);
                                                    const colorMap = [
                                                        '#ffd8bf',
                                                        '#b7eb8f',
                                                        '#d6adff',
                                                        '#87e8de',
                                                        '#ffccc7',
                                                    ]; // 添加颜色映射数组
                                                    return tagNumber >= 1 && tagNumber <= 5 ? ( // 添加有效标签判断
                                                        <span
                                                            key={tag}
                                                            style={{
                                                                fontSize: 12,
                                                                background: colorMap[tagNumber - 1], // 使用颜色映射
                                                                color: 'white', // 添加文字颜色
                                                                borderRadius: 12,
                                                                padding: '2px 8px',
                                                                marginRight: 4,
                                                                display: 'inline-block',
                                                            }}
                                                        >
                                                            {
                                                                [
                                                                    '传统建筑',
                                                                    '特色美食',
                                                                    '地方习俗',
                                                                    '手工艺',
                                                                    '传统服饰',
                                                                ][tagNumber - 1]
                                                            }
                                                        </span>
                                                    ) : null;
                                                })}
                                        </div>
                                    </div>
                                    <div
                                        style={{
                                            fontSize: 12,
                                            color: 'rgba(0, 0, 0, 0.45)',
                                            padding: '8px 24px',
                                        }}
                                    >
                                        发布时间：{item.createdAt && new Date(item.createdAt).toLocaleDateString()}
                                    </div>
                                </div>,
                            ]}
                            // extra={
                            // <img
                            //     width={272}
                            //     height={160}
                            //     alt="logo"
                            //     src={urlMap.defaultUrl + imagesMap.defaultPicturePath + item.imagePath}
                            // />
                            // }
                            extra={
                                item.imagePath ? (
                                    <div
                                        onClick={() => {
                                            const isVideo = item.imagePath.endsWith('.mp4');
                                            Modal.confirm({
                                                icon: null,
                                                width: 800,
                                                content: (
                                                    <div style={{ padding: '20px' }}>
                                                        {' '}
                                                        {/* 添加内边距 */}
                                                        {isVideo ? (
                                                            <video
                                                                controls
                                                                src={
                                                                    urlMap.defaultUrl +
                                                                    imagesMap.defaultPicturePath +
                                                                    item.imagePath
                                                                }
                                                                style={{ width: '100%' }}
                                                            />
                                                        ) : (
                                                            <img
                                                                alt="preview"
                                                                style={{ width: '100%' }}
                                                                src={
                                                                    urlMap.defaultUrl +
                                                                    imagesMap.defaultPicturePath +
                                                                    item.imagePath
                                                                }
                                                            />
                                                        )}
                                                    </div>
                                                ),
                                                footer: null,
                                                centered: true,
                                                closable: true, // 添加关闭图标
                                                maskClosable: true, // 点击遮罩层关闭弹窗
                                            });
                                        }}
                                    >
                                        {item.imagePath.endsWith('.mp4') ? (
                                            <div style={{ position: 'relative' }}>
                                                <video
                                                    muted
                                                    style={{
                                                        width: 272,
                                                        height: 160,
                                                        objectFit: 'cover',
                                                        borderRadius: 4,
                                                        cursor: 'pointer',
                                                    }}
                                                >
                                                    <source
                                                        src={
                                                            urlMap.defaultUrl +
                                                            imagesMap.defaultPicturePath +
                                                            item.imagePath
                                                        }
                                                        type="video/mp4"
                                                    />
                                                </video>
                                                <PlayCircleOutlined
                                                    style={{
                                                        position: 'absolute',
                                                        top: '50%',
                                                        left: '50%',
                                                        transform: 'translate(-50%, -50%)',
                                                        fontSize: 32,
                                                        color: 'rgba(255, 255, 255, 0.8)',
                                                        textShadow: '0 2px 4px rgba(0, 0, 0, 0.3)',
                                                    }}
                                                />
                                            </div>
                                        ) : (
                                            <img
                                                width={272}
                                                height={160}
                                                alt="preview"
                                                style={{
                                                    objectFit: 'cover',
                                                    borderRadius: 4,
                                                    cursor: 'pointer',
                                                }}
                                                src={urlMap.defaultUrl + imagesMap.defaultPicturePath + item.imagePath}
                                            />
                                        )}
                                    </div>
                                ) : null
                            }
                        >
                            <List.Item.Meta
                                avatar={
                                    <Avatar
                                        src={
                                            urlMap.defaultUrl +
                                            imagesMap.defaultAvatarPath +
                                            item?.userId +
                                            '/' +
                                            item?.avatarPath
                                        }
                                    />
                                }
                                title={item?.username}
                            />
                            {item?.content}
                        </List.Item>
                        {expandedItems[index] && (
                            <div
                                style={{
                                    marginTop: -16,
                                    padding: '0 24px',
                                    position: 'relative',
                                    zIndex: 1,
                                }}
                            >
                                <Card
                                    styles={{
                                        body: {
                                            padding: 16,
                                            borderBottom: '1px solid #f0f0f0',
                                            borderTop: 'none',
                                            borderLeft: 'none',
                                            borderRight: 'none',
                                            boxShadow: 'none',
                                            borderRadius: 0,
                                            margin: 0,
                                        },
                                    }}
                                    style={{
                                        borderRadius: 0,
                                        marginLeft: -24,
                                        marginRight: -24,
                                        width: `calc(100% + 48px)`,
                                        boxShadow: 'none',
                                        border: 'none',
                                    }}
                                >
                                    <div
                                        style={{
                                            marginTop: 16,
                                            display: 'flex',
                                            gap: 5,
                                        }}
                                    >
                                        <Input
                                            placeholder="写下你的评论..."
                                            prefix={<UserOutlined />}
                                            value={commentText[index] || ''}
                                            onChange={(e) =>
                                                setCommentText((prev) => ({
                                                    ...prev,
                                                    [index]: e.target.value,
                                                }))
                                            }
                                        />
                                        <Tooltip placement="top" title="发送">
                                            <Button
                                                type="primary"
                                                icon={
                                                    <SendIcon
                                                        style={{
                                                            width: 20,
                                                            height: 20,
                                                            color: '#fff',
                                                        }}
                                                    />
                                                }
                                                onClick={() => handleCommentSubmit(item.postId, index)}
                                            />
                                        </Tooltip>
                                    </div>
                                    {item.comments.length === 0 ? (
                                        <div
                                            style={{
                                                textAlign: 'center',
                                                color: 'rgba(0, 0, 0, 0.45)',
                                                padding: '16px 0',
                                            }}
                                        >
                                            快来发表一条评论吧~
                                        </div>
                                    ) : (
                                        item.comments.map((comment, i) => (
                                            <div
                                                key={i}
                                                style={{
                                                    margin: '8px',
                                                    paddingBottom: '4px',
                                                    borderBottom: i !== item.comments.length - 1 && '1px solid #f0f0f0',
                                                    position: 'relative',
                                                    cursor: 'pointer', // 新增鼠标手势
                                                }}
                                                onMouseEnter={() => setHoveredComment(i)} // 新增悬停状态
                                                onMouseLeave={() => setHoveredComment(null)} // 新增悬停状态
                                            >
                                                <strong>{comment.username}:</strong> &nbsp; {comment.content}
                                                {comment.username === userInfo.username && (
                                                    <Button
                                                        type="link"
                                                        onClick={() => handleDeleteComment(comment.commentId)}
                                                        style={{
                                                            position: 'absolute',
                                                            right: 0,
                                                            opacity: hoveredComment === i ? 1 : 0, // 根据悬停状态控制透明度
                                                            transition: 'opacity 0.3s',
                                                            pointerEvents: hoveredComment === i ? 'auto' : 'none', // 非悬停时禁用点击
                                                        }}
                                                    >
                                                        <DeleteOutlined
                                                            style={{
                                                                color: 'red',
                                                                marginLeft: 5,
                                                            }}
                                                        />
                                                    </Button>
                                                )}
                                            </div>
                                        ))
                                    )}
                                </Card>
                            </div>
                        )}
                    </>
                ) : (
                    <Skeleton active paragraph={{ rows: 3 }} />
                )
            }
        />
    );
}
export default ComList;
